package com.netty.pro.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author xuzn
 * @ClassName: NettyHttpServerHandler
 * @ProjectName netty-pro
 * @date 2020/3/11/21:46
 */

/**
 * SimpleChannelInboundHandler ->ChannelInboundHandler子类
 * HttpObject->客户端和服务端相互通讯的数据被封装成HttpObject类型
 */
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

  // 读取客户端数据
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    System.out.println("context中的channel:" + ctx.channel() + "\n" + " pipeline=" + ctx.pipeline() +
            "\n" + "通过pipeline获取的channel:" + ctx.pipeline().channel());
    System.out.println("当前的context对应的handler:" + ctx.handler());
    // 判断http是不是httprequest请求
    if (msg instanceof HttpRequest) {
      System.out.println("msg的类型是:" + msg.getClass());
      System.out.println("获取客户端地址:" + ctx.channel().remoteAddress());
      // 获取到httpRequest
      HttpRequest httpRequest = (HttpRequest) msg;
      URI uri = new URI(httpRequest.uri());
      if ("/favicon.ico".equals(uri.getPath())) {
        System.out.println("请求了favicon.ico,不作处理");
        return;
      }
      // 回复给浏览器(Http协议)
      ByteBuf content = Unpooled.copiedBuffer("hello,client", CharsetUtil.UTF_8);
      // 构造一个http响应
      FullHttpResponse fullHttpResponse =
              /**
               * 三个参数:版本号,响应状态,内容
               */
              new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
      // 文本类型
      fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
      // 内容长度
      fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
      // 构建完成,返回response
      ctx.writeAndFlush(fullHttpResponse);
    }
  }
}
